package com.my.blog.website.controller.admin;

import com.my.blog.website.constant.WebConst;
import com.my.blog.website.controller.BaseController;
import com.my.blog.website.dao.UserVoMapper;
import com.my.blog.website.dto.LogActions;
import com.my.blog.website.exception.TipException;
import com.my.blog.website.model.Bo.RestResponseBo;
import com.my.blog.website.model.Vo.UserVo;
import com.my.blog.website.model.Vo.UserVoExample;
import com.my.blog.website.service.ILogService;
import com.my.blog.website.service.IUserService;
import com.my.blog.website.utils.Commons;
import com.my.blog.website.utils.PatternKit;
import com.my.blog.website.utils.TaleUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 用户登录，注册，注销
 */
@Controller
@RequestMapping("/admin")
@Transactional(rollbackFor = TipException.class)
public class UserController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserVoMapper userDao;
    @Resource
    private IUserService usersService;

    @Resource
    private ILogService logService;

    @GetMapping(value = "/login")
    public String login() {
        return "admin/login";
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @param remeber_me
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "login")
    @ResponseBody
    public RestResponseBo doLogin(@RequestParam String username, @RequestParam String password, @RequestParam(required = false) String remeber_me, HttpServletRequest request, HttpServletResponse response) {
        Integer error_count = cache.get("login_error_count");
        System.out.println("登录时的密码"+password);
        try {
            UserVo user = usersService.login(username, password);
            request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, user);
            if (StringUtils.isNotBlank(remeber_me)) {
                TaleUtils.setCookie(response, user.getUid());
            }
            logService.insertLog(LogActions.LOGIN.getAction(), null, request.getRemoteAddr(), user.getUid());
            System.out.println("登录时的用户id是"+user.getUid());
            String role = user.getRole();
            System.out.println("用户角色"+user.getRole());
            if ("ADMIN".equals(role)) {
                return RestResponseBo.ok();
            } else {
                return RestResponseBo.ok1();
            }

        } catch (Exception e) {
            error_count = null == error_count ? 1 : error_count + 1;
            if (error_count > 3) {
                return RestResponseBo.fail("您输入密码已经错误超过3次，请10分钟后尝试");
            }
            cache.set("login_error_count", error_count, 10 * 60);
            String msg = "登录失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
    }
    @GetMapping(value = "/register")
    public String register() {
        return "admin/register";
    }
    /**
     * 注册用户
     * @param user 注册的用户信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/register")
    public RestResponseBo zcUser(UserVo user, javax.servlet.http.HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        user.setPassword(TaleUtils.MD5encode(user.getPassword()));
        String count1 = user.getEmail();
        String count2 = user.getUsername();
        UserVoExample example = new UserVoExample();
        UserVoExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(count2);
        long count = userDao.countByExample(example);
        String count4 = TaleUtils.MD5encode(user.getPassword());
        String count5 = TaleUtils.MD5encode(request.getParameter("passwordRepeat"));
        if (count2.equals("")){
            return RestResponseBo.fail("用户名不能为空,请重新输入!");
        }
        else  if (count>=1) {
            return RestResponseBo.fail("该用户已存在，请换一个用户名注册!");
        }
        else  if (count1.equals("")) {
            return RestResponseBo.fail("邮箱号不能为空,请重新输入!");
        }
        else  if (StringUtils.isNotBlank(count1) && !TaleUtils.isEmail(count1)) {
            return RestResponseBo.fail("请输入正确的邮箱格式");
        }
        else  if (StringUtils.isBlank(count4)&&StringUtils.isBlank(count5)){
            return RestResponseBo.fail("密码不能为空!");
        }
        else if (!count4.equals(TaleUtils.MD5encode(count5))){
            return RestResponseBo.fail("两次输入的密码不相同,请重新输入!");
        }
        else {
            usersService.zcUser(user);
            return RestResponseBo.ok("注册成功!");
        }
    }
    /**
     * 注销
     * @param session
     * @param response
     */
    @RequestMapping("/logout")
    public void logout(HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
        Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        try {
            //response.sendRedirect(Commons.site_url());
            response.sendRedirect(Commons.site_login());
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("注销失败", e);
        }
    }
}
